import { request } from './index'

// 部门树缓存
let departmentTreeCache = null;
let departmentTreeCacheTime = 0;
const CACHE_TTL = 5 * 60 * 1000; // 5分钟缓存过期时间

export function getDepartmentList(params) {
  return request({
    url: '/v1/department',
    method: 'get',
    params
  })
}

export function getDepartmentTree(forceRefresh = false) {
  console.log('调用部门树API...');
  
  // 如果有缓存且未过期且不强制刷新，直接返回缓存
  const now = Date.now();
  if (!forceRefresh && departmentTreeCache && (now - departmentTreeCacheTime < CACHE_TTL)) {
    console.log('使用部门树缓存数据');
    return Promise.resolve(departmentTreeCache);
  }
  
  // 否则请求新数据
  return request({
    url: '/v1/department/tree',
    method: 'get'
  }).then(response => {
    // 更新缓存
    departmentTreeCache = response;
    departmentTreeCacheTime = Date.now();
    return response;
  });
}

// 清除部门树缓存的函数，在更新、创建或删除部门后调用
export function clearDepartmentTreeCache() {
  departmentTreeCache = null;
  departmentTreeCacheTime = 0;
}

export function getDepartment(dept_id) {
  console.log('调用获取部门详情API, dept_id:', dept_id, '类型:', typeof dept_id);
  return request({
    url: `/v1/department/${dept_id}`,
    method: 'get'
  })
}

export function getDepartmentWithPermissions(dept_id) {
  return request({
    url: `/v1/department/${dept_id}/with-permissions`,
    method: 'get'
  })
}

export function getDepartmentPermissions(dept_id) {
  return request({
    url: `/v1/department/${dept_id}/permissions`,
    method: 'get'
  })
}

export function setDepartmentPermissions(dept_id, permissions) {
  return request({
    url: `/v1/department/${dept_id}/permissions`,
    method: 'post',
    data: permissions
  })
}

export function addDepartmentPermissions(dept_id, permissions) {
  return request({
    url: `/v1/department/${dept_id}/permissions`,
    method: 'put',
    data: permissions
  })
}

export function removeDepartmentPermissions(dept_id, permissions) {
  return request({
    url: `/v1/department/${dept_id}/permissions`,
    method: 'delete',
    data: permissions
  })
}

export function createDepartment(data) {
  // 创建部门后清除缓存
  clearDepartmentTreeCache();
  return request({
    url: '/v1/department',
    method: 'post',
    data
  })
}

export function updateDepartment(dept_id, data) {
  console.log('调用更新部门API, dept_id:', dept_id, '数据:', data);
  // 更新部门后清除缓存
  clearDepartmentTreeCache();
  return request({
    url: `/v1/department/${dept_id}`,
    method: 'put',
    data
  })
}

export function deleteDepartment(dept_id) {
  // 删除部门后清除缓存
  clearDepartmentTreeCache();
  return request({
    url: `/v1/department/${dept_id}`,
    method: 'delete'
  })
} 